package com.yq.cp.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yq.cp.entity.basics.EquipmentManagement;
import com.yq.cp.entity.basics.OrganizationalStructure;
import com.yq.cp.entity.data.NengKongData;
import com.yq.cp.entity.yw.YwDxfsjl;
import com.yq.cp.mapper.basics.EquipmentManagementMapper;
import com.yq.cp.mapper.basics.OrganizationalStructureMapper;
import com.yq.cp.mapper.yw.YwDxfsjlMapper;
import com.yq.cp.service.yw.YwDxfsjlService;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.management.Query;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Configuration
public class Authorization {

    private static String templateCode1="SMS_474110437";//设备故障断链告警
    private static String templateCode2="SMS_474215433";//设备超过阈值短信告警
    @Resource
    OrganizationalStructureMapper organizationalStructureMapper;
    @Resource
    EquipmentManagementMapper equipmentManagementMapper;
    @Resource
    YwDxfsjlService ywDxfsjlService;
    private static final Logger logger = LoggerFactory.getLogger(Authorization.class);
    public void query() {
        try {
            String key = "1300386381676718567";
            String keySecret = "f680e6b5581f4d6bba1e4d00a1045402";
            Map<String,Object> map = new HashMap();
            map.put("pageNo",1);
            map.put("pageSize",10);
           /* map.put("stationId","1298491919448631809");
            map.put("alarmDeviceSn","00FFC0011557001");
            map.put("nmiCode","41028459350");*/
            //map.put("nmiCode","");
            //map.put("sn","120B40198150131");
             /* map.put("stationId","1298491919448631809");
            map.put("nmiCode","41028459350");*/
           /* map.put("id","1308675217944611083");

            map.put("money","元");
            map.put("year","2023");
            //map.put("month","2023-06");
            map.put("timeZone","8");*/
           /* map.put("time","2023-06-27");
            */
            String body = JSON.toJSONString(map);
            String ContentMd5 = getDigest(body);
            String Date = getGMTTime();
            String path = "/v1/api/userStationList";
            String param = "POST" + "\n" + ContentMd5 + "\n" + "application/json" + "\n" + Date + "\n" + path;
            String sign = HmacSHA1Encrypt(param, keySecret);
            //String url = "https://api.ginlong.com:13333/v1/api/inverterDetail";
            String url = "https://api.ginlong.com:13333" + path;
            //String url = "https://api.ginlonq.com:13333" + path;
            System.out.println(url);
            //System.out.println(url1);
            OkHttpClient client = new OkHttpClient();

            MediaType xmlType = MediaType.parse("application/json;charset=UTF-8");
            okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(xmlType,body);
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(url)
                    .addHeader("Content-type", "application/json;charset=UTF-8")
                    .addHeader("Authorization","API "+key+":"+sign)
                    .addHeader("Content-MD5",ContentMd5)
                    .addHeader("Date",Date)
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            JSONArray jsonArray = JSONObject.parseObject(string).getJSONObject("data").getJSONObject("page").getJSONArray("records");

            logger.info("查询锦浪云：" + string);
            //功率
            String name1="ModBus.逆变器";
            String name2=".有功功率W";
            for (int i = 0; i < jsonArray.size(); i++) {
                String sno = JSONObject.parseObject(jsonArray.get(i).toString()).getString("sno");
                BigDecimal power = JSONObject.parseObject(jsonArray.get(i).toString()).getBigDecimal("power");
//                if ("1d0448".equals(sno)){
////                    NengKongData glData=new NengKongData();
////                    glData.setName(name1+name2);
////                    glData.setValue(power);
////                    glData.setProduceTime(DateTimeUtil.dqsj());
////                    glData.setEnergyCode("Saigeer");
////                    glData.setMacCode(sno);
////                    glData.setHourTime(DateTimeUtil.dqsj());
////                    TimerUtil.list.add(glData);
//                    query1(JSONObject.parseObject(jsonArray.get(i).toString()).getString("id"),sno);
//                }else  if ("19963b".equals(sno)){
////                    NengKongData glData=new NengKongData();
////                    glData.setName(name1+name2);
////                    glData.setValue(power);
////                    glData.setProduceTime(DateTimeUtil.dqsj());
////                    glData.setEnergyCode("MES");
////                    glData.setMacCode(sno);
////                    glData.setHourTime(DateTimeUtil.dqsj());
////                    TimerUtil.list.add(glData);
//                    query1(JSONObject.parseObject(jsonArray.get(i).toString()).getString("id"),sno);
//                }
                this.query1(JSONObject.parseObject(jsonArray.get(i).toString()).getString("id"),sno);

            }
            System.out.println(string);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void query1(String id,String s) {
        try {
            String key = "1300386381676718567";
            String keySecret = "f680e6b5581f4d6bba1e4d00a1045402";
            Map<String,Object> map = new HashMap();
            map.put("pageNo",1);
            map.put("pageSize",10);
            map.put("stationId",id);
           /* map.put("stationId","1298491919448631809");
            map.put("alarmDeviceSn","00FFC0011557001");
            map.put("nmiCode","41028459350");*/
            //map.put("nmiCode","");
            //map.put("sn","120B40198150131");
             /* map.put("stationId","1298491919448631809");
            map.put("nmiCode","41028459350");*/
           /* map.put("id","1308675217944611083");

            map.put("money","元");
            map.put("year","2023");
            //map.put("month","2023-06");
            map.put("timeZone","8");*/
            /* map.put("time","2023-06-27");
             */
            String body = JSON.toJSONString(map);
            String ContentMd5 = getDigest(body);
            String Date = getGMTTime();
            String path = "/v1/api/inverterList";
            String param = "POST" + "\n" + ContentMd5 + "\n" + "application/json" + "\n" + Date + "\n" + path;
            String sign = HmacSHA1Encrypt(param, keySecret);
            //String url = "https://api.ginlong.com:13333/v1/api/inverterDetail";
            String url = "https://api.ginlong.com:13333" + path;
            //String url = "https://api.ginlonq.com:13333" + path;
            System.out.println(url);
            //System.out.println(url1);
            OkHttpClient client = new OkHttpClient();

            MediaType xmlType = MediaType.parse("application/json;charset=UTF-8");
            okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(xmlType,body);
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(url)
                    .addHeader("Content-type", "application/json;charset=UTF-8")
                    .addHeader("Authorization","API "+key+":"+sign)
                    .addHeader("Content-MD5",ContentMd5)
                    .addHeader("Date",Date)
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            JSONArray jsonArray = JSONObject.parseObject(string).getJSONObject("data").getJSONObject("page").getJSONArray("records");

            logger.info("查询锦浪云逆变器：" + string);
            String name1="ModBus.逆变器";
            String name2=".有功功率W";
            for (int i = 0; i < jsonArray.size(); i++) {
                String sno = JSONObject.parseObject(jsonArray.get(i).toString()).getString("sn");//设备编码
                BigDecimal pac = JSONObject.parseObject(jsonArray.get(i).toString()).getBigDecimal("pac");//功率
                QueryWrapper<EquipmentManagement> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("equipment_code",s);
                EquipmentManagement equipmentManagement = equipmentManagementMapper.selectOne(queryWrapper);
                if (equipmentManagement==null || equipmentManagement.getExamine()!=1 || equipmentManagement.getDeleteExamine()==1){
                    return;
                }
                OrganizationalStructure organizationalStructure = organizationalStructureMapper.selectById(equipmentManagement.getSiteId());
                if (organizationalStructure==null || organizationalStructure.getExamine()!=1){
                    return;
                }
                if (pac.compareTo(equipmentManagement.getMaximumThreshold())==1 || pac.compareTo(equipmentManagement.getMaximumThreshold())==-1){

                    YwDxfsjl ywDxfsjl=new YwDxfsjl();
                    ywDxfsjl.setPhone("13647631547");
                    ywDxfsjl.setDxmb(templateCode2);
                    ywDxfsjl.setZdmc(organizationalStructure.getName());
                    ywDxfsjl.setSbmc(equipmentManagement.getName());
                    ywDxfsjl.setSbbm(equipmentManagement.getEquipmentCode());

                    ywDxfsjlService.send(ywDxfsjl);
                }




//                if ("1d0448".equals(s)){
//                    NengKongData glData=new NengKongData();
//                    glData.setName(name1+"3"+name2);
//                    glData.setValue(pac);
//                    glData.setProduceTime(DateTimeUtil.dqsj());
//                    glData.setEnergyCode("Saigeer");
//                    glData.setMacCode(sno);
//                    glData.setHourTime(DateTimeUtil.dqsj());
//                    TimerUtil.list.add(glData);
//                }else  if ("19963b".equals(s)){
//                    NengKongData glData=new NengKongData();
//                    glData.setName(name1+"3"+name2);
//                    glData.setValue(pac);
//                    glData.setProduceTime(DateTimeUtil.dqsj());
//                    glData.setEnergyCode("MES");
//                    glData.setMacCode(sno);
//                    glData.setHourTime(DateTimeUtil.dqsj());
//                    TimerUtil.list.add(glData);
//                }

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

    }
    public static String HmacSHA1Encrypt(String encryptText, String KeySecret) throws Exception
    {
        byte[] data=KeySecret.getBytes("UTF-8");
        SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);

        byte[] text = encryptText.getBytes("UTF-8");
        //瀹屾垚 Mac 鎿嶄綔
        byte[] result = mac.doFinal(text);
        return Base64.encodeBase64String(result);
    }

    public static String  getGMTTime(){

        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); //
        String str = sdf.format(cd.getTime());
        return  str;
    }

    public static String getDigest(String test) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(test.getBytes());
            byte[] b = md.digest();
            result = java.util.Base64.getEncoder().encodeToString(b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }
}